﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace HsServerHa.Utility.Computer
{
    public class DES3Helper
    {
        private static readonly byte[] Key = Encoding.UTF8.GetBytes("my3deskey123456789012345"); // 密钥，必须为 24 字节
        private static readonly byte[] IV = Encoding.UTF8.GetBytes("my3desiv"); // 向量，必须为 8 字节

        // 加密字符串
        public static string Encrypt(string text)
        {
            byte[] inputBytes = Encoding.UTF8.GetBytes(text);
            using (var des3 = new TripleDESCryptoServiceProvider())
            {
                des3.Key = Key;
                des3.IV = IV;
                des3.Mode = CipherMode.CBC;
                des3.Padding = PaddingMode.PKCS7;

                using (var ms = new System.IO.MemoryStream())
                using (var cs = new CryptoStream(ms, des3.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(inputBytes, 0, inputBytes.Length);
                    cs.FlushFinalBlock();
                    return Convert.ToBase64String(ms.ToArray());
                }
            }
        }

        // 解密字符串
        public static string Decrypt(string text)
        {
            byte[] inputBytes = Convert.FromBase64String(text);
            using (var des3 = new TripleDESCryptoServiceProvider())
            {
                des3.Key = Key;
                des3.IV = IV;
                des3.Mode = CipherMode.CBC;
                des3.Padding = PaddingMode.PKCS7;

                using (var ms = new System.IO.MemoryStream())
                using (var cs = new CryptoStream(ms, des3.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(inputBytes, 0, inputBytes.Length);
                    cs.FlushFinalBlock();
                    return Encoding.UTF8.GetString(ms.ToArray());
                }
            }
        }
    }
}
